<?php

// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2030 http://www.jmzh1688.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: lxl
// +----------------------------------------------------------------------


namespace app\comm\controller;

use app\admin\model\AliyunossModel;
use think\Controller;
use think\Db;


class Upload extends  Controller
{


    private $partSize=10*1024*1024;           //允许分片上传最大值

    private $video_maxsize=300*1024*1024;      //视频上传最大文件大小
    private $audio_maxsize=10*1024*1024;      //音频上传最大文件大小
    private $image_maxsize=10*1024*1024;      //图片上传最大文件大小
    private $document_maxsize=10*1024*1024;   //上传办公文件最大文件大小
    private $bigfile_maxszie=500*1024*1024;    //大文件上传允许最大值

    private $img_multifilemaxnum=10;//多图片上传最多图片数量
    private $img_multifilemaxszie=5*1024*1024;//多图片上传最大文件大小
    private $multifile_maxnum=10;   //多文件上传最大数量
    private $multifile_suffix='jpg,png,xls,xlsx,doc,docx,mp4,mp3';   //多文件上传允许上传的文件格式
    private $multifile_maxsize=10*1024*1024;  //多文件上传最大的文件大小

    private $upload_video_suffix='mp4|mp4|mov|mkv|rmvb|wma';//允许上传的视频格式
    private $upload_audio_suffix='mp3';//允许上传的音频格式
    private $upload_image_suffix='jpg,png';//允许上传的图片格式
    private $upload_other_suffix='zip,rzr';//允许上传的其他文件格式
    private $upload_bigfile_suffix='mp4,mp3,avi|mov|mkv|rmvb|wma';//允许上传大文件格式
    private $upload_document_suffix='xls,xlsx,doc,docx';//允许上传的文档格式

    private $local_server_videopath = 'video';//视频存储路径
    private $local_server_audiopath = 'audio';//音频存储路径
    private $local_server_imagepath = 'image';//图片存储路径
    private $local_server_filespath = 'files';//多文件上传统一路径
    private $local_server_documentpath = 'document';//文档存储路径



    public function __construct()
    {
        //$upconfig = new AliyunossModel();
        
        ini_set('max_execution_time', '0');

        $configArr = Db::name('sys_aliyunoss')->where('isdelete=0')->find();

		if($configArr){
			$this->partSize = $configArr['partSize'];
			        $this->video_maxsize = $configArr['video_maxsize'];
			        $this->audio_maxsize = $configArr['audio_maxsize'];
			        $this->image_maxsize = $configArr['image_maxsize'];
			        $this->document_maxsize = $configArr['document_maxsize'];
			        $this->bigfile_maxszie = $configArr['bigfile_maxszie'];

			        $this->img_multifilemaxnum = $configArr['img_multifilemaxnum'];
			        $this->img_multifilemaxszie = $configArr['img_multifilemaxszie'];
			        $this->multifile_maxnum = $configArr['multifile_maxnum'];
			        $this->multifile_suffix = $configArr['multifile_suffix'];
			        $this->multifile_maxsize = $configArr['multifile_maxsize'];

			        $this->upload_video_suffix = $configArr['upload_video_suffix'];
			        $this->upload_audio_suffix = $configArr['upload_audio_suffix'];
			        $this->upload_image_suffix = $configArr['upload_image_suffix'];
			        $this->upload_other_suffix = $configArr['upload_other_suffix'];
			        $this->upload_bigfile_suffix = $configArr['upload_bigfile_suffix'];
			        $this->upload_document_suffix = $configArr['upload_document_suffix'];

			//        $this->local_server_videopath = $configArr['local_server_videopath'];//视频存储路径
			//        $this->local_server_audiopath = $configArr['local_server_audiopath'];//音频存储路径
			//        $this->local_server_imagepath = $configArr['local_server_imagepath'];//图片存储路径
			//        $this->local_server_filespath = $configArr['local_server_filespath'];//多文件上传统一路径
			//        $this->local_server_documentpath = $configArr['local_server_documentpath'];//文档存储路径
		}


    }

    public function uploadimg()
    {
        $extlist='png,jpg,gif,jpeg,doc,docx,xls,xlsx,pdf,zip,cert,txt,pem';
        if (request()->isAjax()) {
            $file = request()->file('file');
            $uploaddir= input("post.uploaddir");
            if($uploaddir==''){$uploaddir='img';}
           

            if($uploaddir=='/'){
               
               // $info = $file->move(ROOT_PATH . 'public', '');
                $info = $file->validate(['ext' =>$extlist ])->move(ROOT_PATH . 'public', '');
                if ($info) {
                    $src = $info->getFilename();
                    return msg('1', $src, 'ok');
                } else {
                    return msg('-1', '', $file->getError());
                }

            }

            $info = $file->validate(['ext' => $extlist])->move(ROOT_PATH . 'public' . DS . 'upload'.'/'.$uploaddir);
            if ($info) {
                $src =  '/upload' .'/'.$uploaddir. '/' . date('Ymd') . '/' . $info->getFilename();
                
                
                   $srcnail =  '/upload' .'/'.$uploaddir. '/' . date('Ymd') . '/small_' . $info->getFilename();
                
                //http://www.lofficiel.net.cn/comm/upload/uploadimg?thumbnailwidth=60&thumbnailheight=90
               
               $thumbnailwidth=120;  $thumbnailheight=0;
            if(array_key_exists('thumbnailwidth',$_GET))
            {
              $thumbnailwidth= $_GET["thumbnailwidth"] ;
              $thumbnailheight= $_GET["thumbnailheight"] ;
              
            }
              $f=ROOT_PATH . 'public'.$src;
              $fnail=ROOT_PATH . 'public'.$srcnail;
              image_center_crop($f,$thumbnailwidth,$thumbnailheight,$fnail);
               
               
               
                return msg('1', $src, 'ok2'.$fnail);
            } else {
                return msg('-1', '', $file->getError());
            }
        }

    }

    /**
     * video 视频文件上传至本地
     */
    public function uploadVideo1(){
        @set_time_limit(5 * 60);
        $targetDir = ROOT_PATH . 'public' . DS . 'upload'.DS.$this->local_server_videopath.'_tmp';
        $uploadDir = ROOT_PATH . 'public' . DS . 'upload'.DS.$this->local_server_videopath.DS.date('Ymd');
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir,0700,true);
        }

        // Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir,0700,true);
        }

        // Get a file name
        if (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
        $filesize = $_FILES["file"]["size"];
        $fileinfo         = pathinfo($fileName);
        $fileExt      = $fileinfo['extension'];   //文件扩展

        if(stripos($this->upload_video_suffix,$fileExt)==false){
            return ['code'=>-1,'msg'=>"上传失败：只能上传 $this->upload_video_suffix 格式的视频文件，请重新选择文件！"];
        }
        if($this->video_maxsize<$filesize){
            $max = $this->formatFileSize($filesize);
            return ['data' => '', 'code' => -1, 'msg' => "上传失败：最大允许上传".$max."大小的视频文件，请重新上传"];
        }
        $filePath = $targetDir . DS . iconv("UTF-8","gb2312",$fileName);
        //        $uploadPath = $uploadDir . DS . iconv("UTF-8","gb2312",$fileName);

        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;

        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                return ('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
                //return msg('-1', '', "Failed to open temp directory");
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DS . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }


        // Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            return ('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');

            //return msg('-1', '', "Failed to open output stream");
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                return ('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
                //return msg('-1', '', "Failed to move uploaded file");
            }
            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                return ('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                //return msg('-1', '', "Failed to open output stream");
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                return ('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                //return msg('-1', '', "Failed to open input stream");
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        @fclose($out);
        @fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
        if ( $done ) {
            $name = uuid();

//            if (!file_exists($uploadDir . DS . $name)) {
            @mkdir($uploadDir . DS . $name,0700,true);
//            }
            $uploadPath = $uploadDir . DS . $name . DS . iconv("UTF-8","gb2312",$fileName);
            if (!$out = @fopen($uploadPath, "wb")) {
                return ('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
                //return msg('-1', '', "Failed to open output stream");
            }

            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
            $url =  'uploads/video/'.date('Ymd'). '/' .$name. '/' .$fileName;
            //return ('{"filepaht" : $url, "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            $ret['msg'] = '上传成功';
            $ret['code'] = 1;
            $ret['data'] = $url;
            //return json($ret);
            return $url;
        }
    }

    public function formatFileSize($size){
        $fileSize =0;
        if(($size/1024)>1024){
            $len = $size/1024/1024;
            $fileSize = round($len,2)."MB";
        }elseif(($size/1024/1024)>1024){
            $len = $size/1024/1024;
            $fileSize = round($len,2)."GB";
        }else{
            $len = $size/1024;
            $fileSize = round($len,2)."KB";
        }
        return $fileSize;
    }
    /**
     * 大文件分片上传
     */
    public function zoneUploadFiles(){
        setlocale(LC_ALL, 'zh_CN.UTF-8');//解决 pathinfo 中文乱码的问题

        $file = request()->file('file');//文件信息
        $param = request()->param();    //传递参数

        $Fileinfo = $file->getInfo();
        if($Fileinfo){
            $fileTotalsize = $param['size'];

            $zoneFileNameinfo = $Fileinfo['name'];
            $zonefileSize     = $Fileinfo['size'];//分片文件大小

            $zonefileinfo         = pathinfo($zoneFileNameinfo);
            $zonefileExt      = $zonefileinfo['extension'];   //文件扩展
            $zonebasename     = $zonefileinfo['basename'];    //带扩展的文件名
            $zonefilename     = $zonefileinfo['filename'];    //不带扩展文件名


            $fileMd5 =$param['fileMd5'];//文件MD5
            $zoneMd5 =$param['zoneMd5'];//分片MD5

            $zonetempDir = ROOT_PATH.'public'.DS.'upload'.DS.'uploadfile_tmp'.DS.date('Ymd').DS.$fileMd5;//临时路径
            $network_path = 'upload'.DS.'uploadfile'.DS.date('Ymd').DS.$fileMd5.'.'.$zonefileExt;;   //网络路径 文件夹+文件名称
            $localPath = 'upload'.DS.'uploadfile'.DS.date('Ymd');   //服务器保存路径 只是文件路径
            $servername = $fileMd5.'.'.$zonefileExt;


            $fileRecorddb = $this->getFileInfo($fileMd5,1);
            $fileZoneRecorddb = $this->getZoneFileInfo($zoneMd5,$fileMd5);//文件分片信息

            //判断是否是分片
            if($fileTotalsize>$Fileinfo['size']){
                if($fileZoneRecorddb==null){

                    if($fileRecorddb==null){

                        $zonefiles['name'] = $param['name'];//源文件名
                        $zonefiles['server_local_name'] = $servername;//服务器生成的文件名
                        $zonefiles['server_local_path'] = $localPath;//服务器储存路径
                        $zonefiles['network_path'] = $network_path;//网络路径，生成的文件夹+系统生成文件名
                        $zonefiles['upload_type'] = 1;//上传类型
                        $zonefiles['md5_value'] = $param['zoneTotalMd5'];//文件MD5值
                        $zonefiles['size'] = $param['zoneTotalSize'];//文件大小

                        $zonefiles['is_merge'] = 0; //是否合并 0 没有合并  1 合并
                        $zonefiles['is_zone'] = 1;  //是否分片 0 否 1是

                        $zonefiles['zone_total'] = $param['zoneTotalCount'];//分片总数
                        $zonefiles['zone_date'] = date('Y-m-d H:i:s',time());//分片时间
                        $zonefiles['file_suffix'] = $zonefileExt;//文件后缀
                        $zonefiles['file_type'] = $param['type'];//文件类型

                        $zonefiles['upload_count'] = 1;//上传统计
                        $zonefiles['download_count'] = 0;//下载统计
                        $zonefiles['create_time'] = time();
                        $zonefiles['create_by'] = session('id');


                        $fileRecordId = Db::name('file_record')->insertGetId($zonefiles);

                    }else {
                        $fileRecordId = $fileRecorddb['id'];
                        $localPath = $fileRecorddb['server_local_path'];

                        //分片且已经合并过了，就不再往下执行，否则继续
                        if ($fileRecorddb['is_zone'] == 1 && $fileRecorddb['is_merge'] == 1) {//如果文件已经合并过了，直接返回
                            return json(['code'=>1, 'data'=>$fileRecorddb, 'msg'=>'文件已经上传']);
                        }

                    }
                    $zone_name = $zoneMd5.'.'.$zonefileExt.".temp";//分片文件名称
                    $info = $file->move($zonetempDir,$zone_name);


                    $fileZoneRecord['zone_name'] = $zone_name;//分片名称
                    $fileZoneRecord['zone_path'] = $zonetempDir;//只存文件夹，合并时，直接读取这个文件所有文件
                    $fileZoneRecord['zone_md5'] = $zoneMd5;//分片MD5
                    $fileZoneRecord['zone_total_count'] = $param['zoneTotalCount'];//总的分片数
                    $fileZoneRecord['zone_total_size'] = $zonefileSize;//总的文件大小
                    $fileZoneRecord['zone_start_size'] = $param['zoneStartSize'];//分片起始位置
                    $fileZoneRecord['zone_end_size'] = $param['zoneEndSize'];//分片结束位置
                    $fileZoneRecord['zone_total_md5'] = $param['zoneTotalMd5'];//总文件的MD5值
                    $fileZoneRecord['zone_now_index'] = $param['zoneNowIndex'];//当前分片索引

                    $fileZoneRecord['zone_suffix'] = $zonefileExt;//分片文件后缀
                    $fileZoneRecord['file_record_id'] = $fileRecordId;//文件记录ID
                    $fileZoneRecord['zone_record_date'] = date('Y-m-d H:i:s',time());//分片记录MD5时间
                    //$zonefiles['zone_check_date'] = $param[''];//上传完成校验日期
                    $fileZoneRecord['create_time'] = time();

                    $zonefileRecordId = Db::name('file_zone_record')->insertGetId($fileZoneRecord);

                    if(!$zonefileRecordId){
                        return json(['code'=>-1, 'data'=>'', 'msg'=>'上传失败：数据保存失败']);
                    }else{
                        return json(['code'=>1, 'data'=>$fileRecorddb, 'msg'=>'上传成功']);
                    }


                }else{
                    return json(['code'=>-1, 'data'=>$fileRecorddb, 'msg'=>'上传成功']);
                }
            }else{

                if($fileRecorddb==null){
                    $serverpath = $localPath;
                    $info = $file->move($serverpath,$servername);

                    $zonefiles['name'] = $param['name'];//源文件名
                    $zonefiles['server_local_name'] = $servername;//服务器生成的文件名
                    $zonefiles['server_local_path'] = $localPath;//服务器储存路径
                    $zonefiles['network_path'] = $network_path;//网络路径，生成的文件夹+系统生成文件名
                    $zonefiles['upload_type'] = 1;//上传类型
                    $zonefiles['md5_value'] = $param['zoneTotalMd5'];//文件MD5值
                    $zonefiles['size'] = $param['zoneTotalSize'];//文件大小

                    $zonefiles['is_merge'] = 1; //是否合并 0 没有合并  1 合并
                    $zonefiles['is_zone'] = 0;  //是否分片 0 否 1是

                    $zonefiles['zone_total'] = $param['zoneTotalCount'];//分片总数
                    $zonefiles['zone_date'] = date('Y-m-d H:i:s',time());//分片时间
                    $zonefiles['file_suffix'] = $zonefileExt;//文件后缀
                    $zonefiles['file_type'] = $param['type'];//文件类型

                    $zonefiles['upload_count'] = 1;//上传统计
                    $zonefiles['download_count'] = 0;//下载统计
                    $zonefiles['create_time'] = time();
                    $zonefiles['create_by'] = session('id');

                    $fileRecordId = Db::name('file_record')->insertGetId($zonefiles);
                    if($fileRecordId){
                        return json(['code'=>1, 'data'=>$fileRecorddb, 'msg'=>'上传成功']);
                    }else{
                        return json(['code'=>-1, 'data'=>'', 'msg'=>'数据保存失败']);
                    }
                }else {
                    //分片且已经合并过了，就不再往下执行，否则继续
                    if ($fileRecorddb['is_zone'] == 1 && $fileRecorddb['is_merge'] == 1) {//如果文件已经合并过了，直接返回
                        $fileRecorddb['uptype'] = 1;
                        return json(['code'=>1, 'data'=>$fileRecorddb, 'msg'=>'文件已经上传']);
                    }else{
                        return json(['code'=>-1, 'data'=>$fileRecorddb, 'msg'=>'继续上传']);
                    }

                }

            }

        }else{
            return msg('-1', '', '请选择文件');
        }

    }

    /**
     *  校验MD5，传入分片MD5和总的MD5，校验当前分片
     */
    public function md5Check(){
        if(request()->isAjax()){
            $param = request()->param();
            $checkType = $param['checkType'];
            $zoneTotalMd5 = $param['zoneTotalMd5'];

            if($checkType==1){
                $result = $this->getFileInfo($zoneTotalMd5,1);
                return $result!='' && $result['is_merge']==1 ? ['code'=>1,'data'=>$result,'msg'=>'文件已经存在'] : ['code'=>'','data'=>'','msg'=>'请选择文件上传'];
            }else{
                $zoneMd5 = $param['zoneMd5'];
                $result = $this->getZoneFileInfo($zoneMd5,$zoneTotalMd5);
                return $result!='' ? ['code'=>1,'data'=>$result,'msg'=>''] : ['code'=>'','data'=>'','msg'=>'分片文件不存在，继续上传'];
            }

        }

    }

    /**
     * 合并文件，前端所有分片上传完成时，发起请求，将所有的文件合并成一个完整的文件，并删除服务器分片文件
     * 前端需要传入总文件的MD5值
     * Author: pan
     */
    public function mergeZoneFile(){
        if(request()->isAjax()){
            $param = request()->param();

            if($param['fileMd5']){

                $fileMd5 = $param['fileMd5'];
                $fileRecorddb = $this->getFileInfo($fileMd5,1);
                if($fileRecorddb==''){
                    return json(['success'=>-1, 'data'=>'', 'msg'=>'上传失败！']);
                }
                $server_local_name = $fileRecorddb['server_local_name'];
                $server_local_path = $fileRecorddb['server_local_path'].DS.$server_local_name;
                $filepath = $fileRecorddb['network_path'];

                if($fileRecorddb['is_zone'] == 1){
                    if ($fileRecorddb['is_merge'] == 1) {
                        //如果文件已经合并过了，直接返回
                        return json(['success'=>1, 'data'=>$fileRecorddb, 'msg'=>'上传成功！']);
                    }
                }else{

                    return json(['success'=>1, 'data'=>$fileRecorddb, 'msg'=>'上传成功！']);
                }

                $zonefileRecorddb = $this->getZoneFileTotalMd5($fileMd5);

                if($zonefileRecorddb){

                    $fp = fopen($server_local_name,"ab");    //合并后的文件名

                    foreach($zonefileRecorddb as $k=>$v){
                        if(!empty($v['zone_path'])) {
                            $path = $v['zone_path'].DS.$v['zone_name'];

                            $frag_file_handler  = fopen($path, 'rb');
                            $frag_file_content = fread($frag_file_handler, filesize($path));
                            fwrite($fp, $frag_file_content);

                            fclose($frag_file_handler);      //销毁分片文件资源
                            unlink($path);     //删除已经合并的分片文件
                            usleep(10000);
                            //unset($handle);
                        }
                    }
                    fclose($fp);

                    if(myCreateDir($fileRecorddb['server_local_path'])){

                        if(!copy($server_local_name,$server_local_path)){
                            return array('success'=>'', '', 'msg'=>'文件拷贝失败');
                        }else{
                            unlink($server_local_name); //删除旧目录下的文件
                            $data['fileInfo'] = $fileRecorddb;
                            return array('success'=>1, '', 'data'=>$data,'msg'=>'上传成功');
                        }

                    }else{
                        return array('success'=>'', '', 'msg'=>'创建文件夹失败');
                    }

                }
            }
        }
    }

    /**
     * 音频上传
     * @return \think\response\Json
     * @author: pan
     * @Date: times
     */
    public function uploadAudio(){
        $file = request()->file('file');//文件信息

        $rest = $this->uploadFile($file,$this->upload_audio_suffix,$this->audio_maxsize,'音频文件',$this->local_server_audiopath);

        return json($rest);
    }

    /**
     * 视频上传
     * @return \think\response\Json
     * @author: pan
     * @Date: times
     */
    public function uploadVideo(){
        $file = request()->file('file');//文件信息

        $rest = $this->uploadFile($file,$this->upload_video_suffix,$this->video_maxsize,'视频文件',$this->local_server_videopath);

        return json($rest);
    }
    /**
     * 文档文件上传
     * @return \think\response\Json
     * @author: pan
     * @Date: times
     */
    public function uploadDoument(){
        $file = request()->file('file');//文件信息
        $rest = $this->uploadFile($file,$this->upload_document_suffix,$this->document_maxsize,'文档文件',$this->local_server_documentpath);
        return json($rest);
    }

    /**
     * 图片文件上传
     * @return \think\response\Json
     * @author: pan
     * @Date: times
     */
    public function uploadImage(){
        $file = request()->file('file');//文件信息
        $rest = $this->uploadFile($file,$this->upload_image_suffix,$this->image_maxsize,'图片文件',$this->local_server_imagepath);

        return json($rest);
    }

    /**
     * 上传文件
     * @param $file     上传的文件信息
     * @param $suffix   允许上传的文件后缀
     * @param $maxsize  允许上传最大的文件大小
     * @param $tile     上文件标题
     * @param $savepath 文件保存路径
     * @return array    返回值
     * @author: pan
     * @Date: times
     */
    public function uploadFile($file,$suffix,$maxsize,$tile,$savepath){

        $Fileinfo = $file->getInfo();

        if($Fileinfo) {
            $filetype  = $Fileinfo['type'];
            $filesize  = $Fileinfo['size'];
            $fileName  = $Fileinfo['name'];
            $fileinfo  = pathinfo($fileName);
            $fileExt   = $fileinfo['extension'];   //文件扩展

            if(stripos($suffix,$fileExt)===false){
                return ['code'=>-1,'msg'=>"上传失败：只能上传 $suffix 格式的$tile ，请重新选择文件！"];
            }
            if($maxsize<$filesize){
                $max = $this->formatFileSize($filesize);
                return ['data' => '', 'code' => -1, 'msg' => "上传失败：最大允许上传".$max."大小的$tile ，请重新上传"];
            }

            $SavefilePath = 'upload' . DS .$savepath;

            $info = $file->move(ROOT_PATH . 'public' . DS .$SavefilePath);
            if ($info) {
                $src =  $SavefilePath. DS . date('Ymd') . DS .$info->getFilename();

                $addfiles['name'] = $fileName;//源文件名
                $addfiles['server_local_name'] = $info->getFilename();//服务器生成的文件名
                $addfiles['server_local_path'] = $SavefilePath. DS . date('Ymd');//服务器储存路径
                $addfiles['network_path'] = $src;//网络路径，生成的文件夹+系统生成文件名
                $addfiles['upload_type'] = 3;//上传类型
                $addfiles['size'] = $filesize;//文件大小

                $addfiles['is_merge'] = 1; //是否合并 0 没有合并  1 合并
                $addfiles['is_zone'] = 0;  //是否分片 0 否 1是

                $addfiles['file_suffix'] = $fileExt;//文件后缀
                $addfiles['file_type'] = $filetype;//文件类型

                $addfiles['upload_count'] = 1;//上传统计
                $addfiles['download_count'] = 0;//下载统计
                $addfiles['create_time'] = time();
                $addfiles['create_by'] = session('id');//操作人id
                $fileRecordId = Db::name('file_record')->insertGetId($addfiles);

                if($fileRecordId){
                    $refileinfo['id'] = $fileRecordId;
                    $refileinfo['serverpath'] = $src;
                    $refileinfo['path'] = $src;
                    $refileinfo['size'] = $filesize;
                    $refileinfo['type'] = $filetype;
                    return ['code'=>1, 'data'=>$refileinfo, 'msg'=>'上传成功'];
                }else{
                    return ['code'=>-1, 'data'=>'', 'msg'=>'数据保存失败'];
                }

            } else {
                return array('code'=>-1, 'data'=>'', 'msg'=>$file->getError());
            }
        }else{
            return array('code'=>-1, 'data'=>'', 'msg'=>'上传文件不能为空！');
        }
    }
    /**
     * 删除分片文件
     * Author: pan
     */
    public function delZoneFile(){

    }

    /**
     * 删除单文件
     * @author: pan
     * @Date: times
     */
    public function delFile(){
        if(request()->isAjax()) {
            $param = request()->param();
			$id = $param['id'];
			$files = $param['files'];
			$fileid = $param['fileid'];//文件资源表id

            if($fileid){
                $u['isdelete'] = 1;
                $result = Db::name('file_record')->where("id=$fileid")->update($u);
                if($result){
                    return array('code'=>1, 'data'=>'', 'msg'=>'删除成功');
                }else{
                    return array('code'=>-1, 'data'=>'', 'msg'=>'删除失败');
                }
            }else{
                return array('code'=>-1, 'data'=>'', 'msg'=>'删除失败');
            }
            //dump($param);die;
        }else{
            return array('code'=>-1, 'data'=>'', 'msg'=>'请求格式错误');
        }
    }

    /**
     * 获取文件信息
     * @param $md5_value MD5值
     * @param $type     1 文件类型 2 图片类型
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * @author: pan
     * @Date:
     */
    public function getFileInfo($md5_value,$type){
        $reslt = Db::name('file_record')->where("md5_value='$md5_value' and upload_type=$type")->find();
        return $reslt;
    }

    /**
     * 根据总文件的MD5值，查询出当前文件的所有分片文件信息
     * @param $zoneTotalMd5
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * @author: pan
     * @Date: times
     */
    public function getZoneFileTotalMd5($zoneTotalMd5){
        $reslt = Db::name('file_zone_record')->where("zone_total_md5='$zoneTotalMd5'")->select();
        return $reslt;
    }
    /**
     * @param $zoneMd5      分片MD5
     * @param $zoneTotalMd5 总文件MD5
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * @author: pan
     * @Date: times
     */
    public function getZoneFileInfo($zoneMd5,$zoneTotalMd5){
        $where = "zone_md5='$zoneMd5' and zone_total_md5='$zoneTotalMd5'";
        $reslt = Db::name('file_zone_record')->where($where)->find();
        return $reslt;
    }

    /***************************************************阿里云OSS 上传***************************************************/

    public function ossUploadFile(){

    }

}
